package com.henry.librarymng;

import java.util.ArrayList;
import java.util.Date;

public class Library {
    String libraryName;
    String libraryAddress;
    ArrayList<BookEntry> books;

    static String libraryOpeningTime;

    public Library(String name, String address) {
        this.libraryName = name;
        this.libraryAddress = address;
        this.books = new ArrayList<BookEntry>();
    }

    public static void setOpeningTime(String openTime) {
        libraryOpeningTime = openTime;
    }

    public void addBook(String bookName) {
        for (BookEntry existingBook : books) {
            if (existingBook.getBookTitle().equals(bookName)) {
                existingBook.addCopies();
                return;
            }
        }
        books.add(new BookEntry(bookName, books.size()));
    }

    public BookEntry borrow(String readerID, String bookName) throws Exception {
        ArrayList<BookEntry> searchResult = this.searchBook(bookName);
        if (searchResult.isEmpty()) throw new Exception("Sorry, we don't have this book.");
        else {
            for (BookEntry book : searchResult) {
                book.borrowing(readerID, new Date());
                return book;
            }
        }
        return null;
    }

    public BookEntry returnBook(String readerID, String bookName) throws Exception {
        ArrayList<BookEntry> searchResult = this.searchBook(bookName);
        if (searchResult.isEmpty()) throw new Exception("Sorry, we don't have this book.");
        else {
            for (BookEntry book : searchResult) {
                book.returning(readerID);
                return book;
            }
        }
        return null;
    }

    public ArrayList<BookEntry> searchBook(String bookName) {
        ArrayList<BookEntry> searchResults = new ArrayList<BookEntry>();
        for (BookEntry book : books) {
            if (book.getBookTitle().contains(bookName)) {
                searchResults.add(book);
            }
        }
        return searchResults;
    }

    public ArrayList<BookEntry> availableBooks() {
        ArrayList<BookEntry> searchResults = new ArrayList<BookEntry>();
        for (BookEntry book : books) {
            if (book.available()) {
                searchResults.add(book);
            }
        }
        return searchResults;
    }

    public String getLibraryInfo() {
        return this.libraryName + "\n" + this.libraryAddress + "\n" + libraryOpeningTime;
    }

    public String getLibraryName() { return libraryName; }
}
